package com.example.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.domain.OperationalLogs;
import com.example.blog.domain.Response;
import com.example.blog.dto.operationalLogs.AdminSelectOperationLogDto;
import com.example.blog.note.LogInfo;
import com.example.blog.note.Permissions;
import com.example.blog.service.impl.OperationalLogsServiceImpl;
import com.example.blog.dto.publicDto.PageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/operationalLogs")
@Transactional
@Validated
public class OperationalLogsController {

    private final OperationalLogsServiceImpl operationalLogsService;
    @Autowired
    public OperationalLogsController(OperationalLogsServiceImpl operationalLogsService){
        this.operationalLogsService = operationalLogsService;
    }

    //获取所有的操作日志
    @Permissions("/operationalLogs/getAll")
    @LogInfo("获取所有的操作日志")
    @PostMapping("/getAll")
    public Response getAll(@RequestBody AdminSelectOperationLogDto logsPage){
        IPage page = new Page(logsPage.getIndex(),logsPage.getPage());
        LambdaQueryWrapper<OperationalLogs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(Objects.nonNull(logsPage.getDateTime()),OperationalLogs::getTime,logsPage.getDateTime())
                .eq(logsPage.getTypes() != null,OperationalLogs::getType, logsPage.getTypes())
                    .orderByDesc(OperationalLogs::getTime);
        Optional.ofNullable(logsPage.getCondition())
                .ifPresent(s->{
                    queryWrapper.and(wrapper->wrapper.like(OperationalLogs::getUser, logsPage.getCondition())
                            .like(OperationalLogs::getAdmin, logsPage.getCondition())
                            .or()
                            .like(OperationalLogs::getContent, logsPage.getCondition()));
                });


        return new Response(Response.SUCCEED_CODE,"获取所有的操作日志",operationalLogsService.page(page,queryWrapper));
    }

    //删除日志
    @Permissions("/operationalLogs/deleteAdmin")
    @LogInfo("删除日志")
    @DeleteMapping("/deleteAdmin/{id}")
    public Response deleteAdminTotal(@PathVariable("id") long id){
        operationalLogsService.removeById(id);
        return new Response(Response.SUCCEED_CODE,"删除日志",null);
    }
}
